import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.path import Path
import numpy as np


def create_architecture_diagram():
    fig, ax = plt.subplots(figsize=(12, 8))

    # 定义组件和颜色
    components = {
        'Input': (1, 9, 'lightgray'),
        'Backbone': (2, 9, 'skyblue'),
        'LAMFPN': (3, 9, 'lightgreen'),
        'Feature Pyramid': (3, 7.5, 'gold'),
        'LCM': (4, 10.5, 'lightsalmon'),
        'ADEM': (4, 7.5, 'plum'),
        'Detection Head': (5, 9, 'lightcoral'),
        'Output': (6, 9, 'lightgray')
    }

    # 绘制组件盒子
    for name, (x, y, color) in components.items():
        width = 2.5
        height = 1.5 if name not in ['LCM', 'ADEM'] else 1.2
        rect = patches.Rectangle((x - width / 2, y - height / 2), width, height,
                                 linewidth=1, edgecolor='black', facecolor=color, alpha=0.8)
        ax.add_patch(rect)
        ax.text(x, y, name, ha='center', va='center', fontsize=12, fontweight='bold')

    # 绘制箭头连接
    connections = [
        ('Input', 'Backbone'),
        ('Backbone', 'LAMFPN'),
        ('LAMFPN', 'Feature Pyramid'),
        ('Feature Pyramid', 'ADEM'),
        ('Feature Pyramid', 'Detection Head'),
        ('ADEM', 'Detection Head'),
        ('LCM', 'Detection Head'),
        ('Detection Head', 'Output')
    ]

    for start, end in connections:
        start_x, start_y, _ = components[start]
        end_x, end_y, _ = components[end]

        # 确定箭头的位置和方向
        if start == 'LAMFPN' and end == 'Feature Pyramid':
            dx, dy = 0, -0.75
            ax.arrow(start_x, start_y - 0.75, dx, dy, head_width=0.15,
                     head_length=0.1, fc='black', ec='black', length_includes_head=True)
        elif start == 'Feature Pyramid' and end == 'Detection Head':
            dx, dy = 2, 1.5
            ax.arrow(start_x + 1.25, start_y, dx, dy, head_width=0.15,
                     head_length=0.1, fc='black', ec='black', length_includes_head=True)
        elif start == 'Feature Pyramid' and end == 'ADEM':
            dx, dy = 1, 0
            ax.arrow(start_x + 1.25, start_y, dx, dy, head_width=0.15,
                     head_length=0.1, fc='black', ec='black', length_includes_head=True)
        elif start == 'LCM' and end == 'Detection Head':
            dx, dy = 1, -1.5
            ax.arrow(start_x + 1.25, start_y, dx, dy, head_width=0.15,
                     head_length=0.1, fc='black', ec='black', length_includes_head=True)
        else:
            dx, dy = end_x - start_x, end_y - start_y
            ax.arrow(start_x + 1.25, start_y, dx - 1.25, dy, head_width=0.15,
                     head_length=0.1, fc='black', ec='black', length_includes_head=True)

    # 添加标题和图例
    ax.set_title('AlgaeDiff-Net Architecture', fontsize=16, fontweight='bold')

    # 添加模块说明
    module_desc = {
        'LAM': 'Local Affinity Module',
        'LCM': 'Local Collaborating Module',
        'ADEM': 'Auxiliary Density Estimation Module'
    }

    y_pos = 4
    for abbr, desc in module_desc.items():
        ax.text(9, y_pos, f"{abbr}: {desc}", fontsize=10)
        y_pos -= 0.5

    # 设置轴范围和关闭刻度
    ax.set_xlim(0, 10)
    ax.set_ylim(6, 12)
    ax.axis('off')

    plt.tight_layout()
    plt.savefig('algaediff_net_architecture.png', dpi=300, bbox_inches='tight')
    plt.show()


create_architecture_diagram()

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np


def create_lam_diagram():
    fig, ax = plt.subplots(figsize=(12, 8))

    # 设置背景色
    ax.set_facecolor("#f8f8f8")

    # 定义组件和颜色
    block_height = 0.8
    block_width = 2.5

    # 定义主要组件位置
    feature_map_x1 = 1
    feature_map_y1 = 6

    feature_map_x2 = 1
    feature_map_y2 = 4

    # 绘制输入特征图
    ax.add_patch(patches.Rectangle((feature_map_x1, feature_map_y1), block_width, block_height,
                                   edgecolor='black', facecolor='#AED6F1', alpha=0.8))
    ax.text(feature_map_x1 + block_width / 2, feature_map_y1 + block_height / 2,
            "Target Feature\n(Higher Resolution)",
            ha='center', va='center', fontsize=10)

    ax.add_patch(patches.Rectangle((feature_map_x2, feature_map_y2), block_width, block_height,
                                   edgecolor='black', facecolor='#D6EAF8', alpha=0.8))
    ax.text(feature_map_x2 + block_width / 2, feature_map_y2 + block_height / 2,
            "Source Feature\n(Lower Resolution)",
            ha='center', va='center', fontsize=10)

    # 添加上采样箭头
    ax.annotate('', xy=(feature_map_x2 + block_width / 2, feature_map_y1),
                xytext=(feature_map_x2 + block_width / 2, feature_map_y2 + block_height),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
    ax.text(feature_map_x2 + block_width / 2, feature_map_y2 + block_height + 0.5,
            "Upsample", ha='center', fontsize=9)

    # 连接箭头
    ax.annotate('', xy=(feature_map_x1 + block_width + 1, feature_map_y1 + block_height / 2),
                xytext=(feature_map_x1 + block_width, feature_map_y1 + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    ax.annotate('', xy=(feature_map_x2 + block_width + 1, feature_map_y1 + block_height / 2),
                xytext=(feature_map_x2 + block_width, feature_map_y2 + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制拼接
    concat_x = feature_map_x1 + block_width + 1
    concat_y = 5
    concat_height = 2

    ax.add_patch(patches.Rectangle((concat_x, concat_y), block_width, concat_height,
                                   edgecolor='black', facecolor='#D5F5E3', alpha=0.8))
    ax.text(concat_x + block_width / 2, concat_y + concat_height / 2,
            "Concatenation", ha='center', va='center', fontsize=10)

    # 注意力计算
    attention_x = concat_x + block_width + 1
    attention_y = concat_y

    ax.annotate('', xy=(attention_x, concat_y + concat_height / 2),
                xytext=(concat_x + block_width, concat_y + concat_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    ax.add_patch(patches.Rectangle((attention_x, attention_y), block_width, concat_height,
                                   edgecolor='black', facecolor='#FADBD8', alpha=0.8))
    ax.text(attention_x + block_width / 2, attention_y + concat_height / 2,
            "Attention Conv\n3x3, ReLU", ha='center', va='center', fontsize=10)

    # 注意力权重
    weight_x = attention_x + block_width + 1
    weight_y = attention_y

    ax.annotate('', xy=(weight_x, attention_y + concat_height / 2),
                xytext=(attention_x + block_width, attention_y + concat_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    ax.add_patch(patches.Rectangle((weight_x, weight_y), block_width, concat_height,
                                   edgecolor='black', facecolor='#F5CBA7', alpha=0.8))
    ax.text(weight_x + block_width / 2, weight_y + concat_height / 2,
            "Attention Weights\n1x1 Conv + Softmax", ha='center', va='center', fontsize=10)

    # 权重应用
    apply_x = weight_x + block_width + 1
    apply_y = weight_y

    ax.annotate('', xy=(apply_x, weight_y + concat_height / 2),
                xytext=(weight_x + block_width, weight_y + concat_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    ax.add_patch(patches.Rectangle((apply_x, apply_y), block_width, concat_height,
                                   edgecolor='black', facecolor='#D7BDE2', alpha=0.8))
    ax.text(apply_x + block_width / 2, apply_y + concat_height / 2,
            "Weighted Feature\nFusion", ha='center', va='center', fontsize=10)

    # 最终卷积
    final_x = apply_x + block_width + 1
    final_y = apply_y

    ax.annotate('', xy=(final_x, apply_y + concat_height / 2),
                xytext=(apply_x + block_width, apply_y + concat_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    ax.add_patch(patches.Rectangle((final_x, final_y), block_width, concat_height,
                                   edgecolor='black', facecolor='#AED6F1', alpha=0.8))
    ax.text(final_x + block_width / 2, final_y + concat_height / 2,
            "Enhanced Feature\n3x3 Conv + ReLU", ha='center', va='center', fontsize=10)

    # 添加标题和标注
    ax.text(8, 7.5, "Local Affinity Module (LAM)\n",
            ha='center', fontsize=14, fontweight='bold')

    ax.text(8, 2, "LAM enhances local feature consistency by\ngenerating adaptive attention weights for feature fusion",
            ha='center', fontsize=10, style='italic')

    # 通道注意力机制
    ax.add_patch(patches.Rectangle((5, 3), 6, 0.8,
                                   edgecolor='black', facecolor='#FDEBD0', alpha=0.8, linestyle='--'))
    ax.text(8, 3.4, "Optional Channel Attention", ha='center', fontsize=10)

    # 设置轴范围和关闭刻度
    ax.set_xlim(0, 16)
    ax.set_ylim(1.5, 8)
    ax.axis('off')

    plt.tight_layout()
    plt.savefig('lam_module_diagram.png', dpi=300, bbox_inches='tight')
    plt.show()


create_lam_diagram()

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np


def create_lcm_diagram():
    fig, ax = plt.subplots(figsize=(12, 8))

    # 设置背景色
    ax.set_facecolor("#f8f8f8")

    # 定义组件尺寸
    block_width = 2.0
    block_height = 0.8

    # 定义主要组件位置
    start_x = 1
    start_y = 5

    # 定义颜色
    colors = {
        'box': '#D6EAF8',
        'roi': '#FADBD8',
        'feat': '#D5F5E3',
        'mapper': '#F5CBA7',
        'output': '#D7BDE2'
    }

    # 绘制初始检测框
    ax.add_patch(patches.Rectangle((start_x, start_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['box'], alpha=0.8))
    ax.text(start_x + block_width / 2, start_y + block_height / 2,
            "Predicted\nBoxes",
            ha='center', va='center', fontsize=10)

    # 绘制特征金字塔
    fpn_x = start_x
    fpn_y = start_y + 2
    fpn_height = 1.6
    ax.add_patch(patches.Rectangle((fpn_x, fpn_y), block_width, fpn_height,
                                   edgecolor='black', facecolor='#FDEBD0', alpha=0.8))
    ax.text(fpn_x + block_width / 2, fpn_y + fpn_height / 2,
            "Feature\nPyramid",
            ha='center', va='center', fontsize=10)

    # 连接FPN到ROI Pooling
    ax.annotate('', xy=(fpn_x + block_width + 1, fpn_y + fpn_height / 2),
                xytext=(fpn_x + block_width, fpn_y + fpn_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    ax.annotate('', xy=(fpn_x + block_width + 1, start_y + block_height / 2),
                xytext=(fpn_x + block_width, start_y + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制ROI池化
    roi_x = fpn_x + block_width + 1
    roi_y = start_y + 1
    roi_height = 1.6
    ax.add_patch(patches.Rectangle((roi_x, roi_y), block_width, roi_height,
                                   edgecolor='black', facecolor=colors['roi'], alpha=0.8))
    ax.text(roi_x + block_width / 2, roi_y + roi_height / 2,
            "ROI Pooling\n(7x7)",
            ha='center', va='center', fontsize=10)

    # ROI Pooling到特征降维
    feat_x = roi_x + block_width + 1
    feat_y = roi_y
    ax.annotate('', xy=(feat_x, roi_y + roi_height / 2),
                xytext=(roi_x + block_width, roi_y + roi_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制特征降维
    ax.add_patch(patches.Rectangle((feat_x, feat_y), block_width, roi_height,
                                   edgecolor='black', facecolor=colors['feat'], alpha=0.8))
    ax.text(feat_x + block_width / 2, feat_y + roi_height / 2,
            "Feature\nDimension\nReduction",
            ha='center', va='center', fontsize=10)

    # 特征降维到LCM映射
    mapper_x = feat_x + block_width + 1
    mapper_y = feat_y
    ax.annotate('', xy=(mapper_x, feat_y + roi_height / 2),
                xytext=(feat_x + block_width, feat_y + roi_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制LCM映射器
    ax.add_patch(patches.Rectangle((mapper_x, mapper_y), block_width, roi_height,
                                   edgecolor='black', facecolor=colors['mapper'], alpha=0.8))
    ax.text(mapper_x + block_width / 2, mapper_y + roi_height / 2,
            "LCM Mapper\nNetwork",
            ha='center', va='center', fontsize=10)

    # LCM映射到偏移量
    offset_x = mapper_x + block_width + 1
    offset_y = mapper_y
    ax.annotate('', xy=(offset_x, mapper_y + roi_height / 2),
                xytext=(mapper_x + block_width, mapper_y + roi_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制框偏移量
    ax.add_patch(patches.Rectangle((offset_x, offset_y), block_width, roi_height,
                                   edgecolor='black', facecolor=colors['output'], alpha=0.8))
    ax.text(offset_x + block_width / 2, offset_y + roi_height / 2,
            "Box\nOffsets\n(Δx, Δy, Δw, Δh)",
            ha='center', va='center', fontsize=10)

    # 偏移量应用
    apply_x = offset_x
    apply_y = start_y

    # 绘制箭头从偏移量到应用
    ax.annotate('', xy=(apply_x + block_width / 2, apply_y + block_height),
                xytext=(apply_x + block_width / 2, offset_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制应用偏移量
    ax.add_patch(patches.Rectangle((apply_x, apply_y), block_width, block_height,
                                   edgecolor='black', facecolor='#AED6F1', alpha=0.8))
    ax.text(apply_x + block_width / 2, apply_y + block_height / 2,
            "Apply\nOffsets",
            ha='center', va='center', fontsize=10)

    # 最终调整后的框
    final_x = apply_x + block_width + 1
    final_y = apply_y

    # 绘制箭头到最终框
    ax.annotate('', xy=(final_x, apply_y + block_height / 2),
                xytext=(apply_x + block_width, apply_y + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制最终调整框
    ax.add_patch(patches.Rectangle((final_x, final_y), block_width, block_height,
                                   edgecolor='black', facecolor='#AED6F1', alpha=0.8))
    ax.text(final_x + block_width / 2, final_y + block_height / 2,
            "Refined\nBoxes",
            ha='center', va='center', fontsize=10)

    # 添加标题和注释
    ax.text(7, 7.5, "Local Collaborating Module (LCM)",
            ha='center', fontsize=14, fontweight='bold')

    # 添加模块说明
    ax.text(7, 4,
            "Box refinement through local context modeling\nLearns contextual relationships to refine box positions",
            ha='center', fontsize=10, style='italic')

    # LCM Mapper Network详解
    ax.add_patch(patches.Rectangle((10, 4), 4, 2.5,
                                   edgecolor='black', facecolor='#FDEBD0', alpha=0.6, linestyle='-'))

    ax.text(12, 6.3, "LCM Mapper Network", ha='center', fontsize=10, fontweight='bold')

    # 内部架构
    internal_y = 6.0
    ax.text(10.5, internal_y, "Linear(256, 512)", ha='left', fontsize=9)
    internal_y -= 0.3
    ax.text(10.5, internal_y, "GELU", ha='left', fontsize=9)
    internal_y -= 0.3
    ax.text(10.5, internal_y, "Linear(512, 256)", ha='left', fontsize=9)
    internal_y -= 0.3
    ax.text(10.5, internal_y, "Linear(256, 4)", ha='left', fontsize=9)
    internal_y -= 0.3
    ax.text(10.5, internal_y, "Output: (Δx, Δy, Δw, Δh)", ha='left', fontsize=9)

    # 设置轴范围和关闭刻度
    ax.set_xlim(0, 15)
    ax.set_ylim(3.5, 8)
    ax.axis('off')

    plt.tight_layout()
    plt.savefig('lcm_module_diagram.png', dpi=300, bbox_inches='tight')
    plt.show()


create_lcm_diagram()

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np


def create_adem_diagram():
    fig, ax = plt.subplots(figsize=(12, 8))

    # 设置背景色
    ax.set_facecolor("#f8f8f8")

    # 定义组件尺寸
    block_width = 2.0
    block_height = 0.8

    # 定义主要组件位置
    start_x = 1
    fpn_y = 6

    # 定义颜色
    colors = {
        'p3': '#D6EAF8',
        'p4': '#AED6F1',
        'p5': '#7FB3D5',
        'fusion': '#D5F5E3',
        'density': '#FADBD8',
        'uncertainty': '#F5CBA7',
        'final': '#D7BDE2'
    }

    # 绘制特征金字塔层
    pyramids = ['P3', 'P4', 'P5']
    pyramid_xs = [start_x, start_x, start_x]
    pyramid_ys = [fpn_y, fpn_y - 1.2, fpn_y - 2.4]
    pyramid_colors = [colors['p3'], colors['p4'], colors['p5']]

    for i, (p, y, color) in enumerate(zip(pyramids, pyramid_ys, pyramid_colors)):
        ax.add_patch(patches.Rectangle((start_x, y), block_width, block_height,
                                       edgecolor='black', facecolor=color, alpha=0.8))
        ax.text(start_x + block_width / 2, y + block_height / 2,
                f"{p}\nFeature",
                ha='center', va='center', fontsize=10)

    # 绘制特征变换模块
    transform_x = start_x + block_width + 1

    for i, y in enumerate(pyramid_ys):
        ax.annotate('', xy=(transform_x, y + block_height / 2),
                    xytext=(start_x + block_width, y + block_height / 2),
                    arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

        ax.add_patch(patches.Rectangle((transform_x, y), block_width, block_height,
                                       edgecolor='black', facecolor=colors['fusion'], alpha=0.8))
        ax.text(transform_x + block_width / 2, y + block_height / 2,
                f"Transform\n3x3 Conv",
                ha='center', va='center', fontsize=10)

    # 上采样和特征融合
    fusion_x = transform_x + block_width + 1
    fusion_y = fpn_y - 1.2
    fusion_height = 2 * block_height

    # P4到融合层
    ax.annotate('', xy=(fusion_x, fusion_y + fusion_height / 2),
                xytext=(transform_x + block_width, pyramid_ys[0] + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # P5到融合层
    ax.annotate('', xy=(fusion_x, fusion_y + fusion_height / 2),
                xytext=(transform_x + block_width, pyramid_ys[1] + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # P6到融合层
    ax.annotate('', xy=(fusion_x, fusion_y + fusion_height / 2),
                xytext=(transform_x + block_width, pyramid_ys[2] + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制融合模块
    ax.add_patch(patches.Rectangle((fusion_x, fusion_y - 0.5), block_width, fusion_height,
                                   edgecolor='black', facecolor=colors['fusion'], alpha=0.8))
    ax.text(fusion_x + block_width / 2, fusion_y + fusion_height / 2 - 0.5,
            "Feature\nFusion",
            ha='center', va='center', fontsize=10)

    # 密度预测和不确定性分支
    density_x = fusion_x + block_width + 1
    density_y = fpn_y - 0.2
    uncertainty_y = fpn_y - 2.2

    # 融合到密度预测
    ax.annotate('', xy=(density_x, density_y + block_height / 2),
                xytext=(fusion_x + block_width, fusion_y + fusion_height / 4 - 0.5),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 融合到不确定性预测
    ax.annotate('', xy=(density_x, uncertainty_y + block_height / 2),
                xytext=(fusion_x + block_width, fusion_y - fusion_height / 4 - 0.5),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制密度预测分支
    ax.add_patch(patches.Rectangle((density_x, density_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['density'], alpha=0.8))
    ax.text(density_x + block_width / 2, density_y + block_height / 2,
            "Density\nPrediction",
            ha='center', va='center', fontsize=10)

    # 绘制不确定性预测分支
    ax.add_patch(patches.Rectangle((density_x, uncertainty_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['uncertainty'], alpha=0.8))
    ax.text(density_x + block_width / 2, uncertainty_y + block_height / 2,
            "Uncertainty\nEstimation",
            ha='center', va='center', fontsize=10)

    # 最终密度图
    final_x = density_x + block_width + 1
    final_y = fpn_y - 1.2

    # 密度预测到最终图
    ax.annotate('', xy=(final_x, final_y + block_height / 2),
                xytext=(density_x + block_width, density_y + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 不确定性到最终图
    ax.annotate('', xy=(final_x, final_y + block_height / 2),
                xytext=(density_x + block_width, uncertainty_y + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 绘制最终密度图
    ax.add_patch(patches.Rectangle((final_x, final_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['final'], alpha=0.8))
    ax.text(final_x + block_width / 2, final_y + block_height / 2,
            "Final\nDensity Map",
            ha='center', va='center', fontsize=10)

    # 添加标题和注释
    ax.text(7, 7.5, "Auxiliary Density Estimation Module (ADEM)",
            ha='center', fontsize=14, fontweight='bold')

    # 添加模块说明
    ax.text(7, 2.5, "Generates density map to provide density prior knowledge\nImproves detection in crowded scenes",
            ha='center', fontsize=10, style='italic')

    # 密度图利用方式
    ax.add_patch(patches.Rectangle((final_x + block_width + 0.5, final_y - 1), 4, 2.5,
                                   edgecolor='black', facecolor='#FDEBD0', alpha=0.6, linestyle='-'))

    ax.text(final_x + block_width + 2.5, final_y + 1.3, "Density Map Usage", ha='center', fontsize=10,
            fontweight='bold')

    usage_text = [
        "1. Confidence enhancement",
        "2. Non-maximum suppression guidance",
        "3. Small object sensitivity increase",
        "4. Auxiliary supervision signal"
    ]

    y_pos = final_y + 0.8
    for text in usage_text:
        y_pos -= 0.4
        ax.text(final_x + block_width + 1, y_pos, text, ha='left', fontsize=9)

    # 设置轴范围和关闭刻度
    ax.set_xlim(0, 15)
    ax.set_ylim(2, 8)
    ax.axis('off')

    plt.tight_layout()
    plt.savefig('adem_module_diagram.png', dpi=300, bbox_inches='tight')
    plt.show()

create_adem_diagram()

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np


def create_system_architecture(save_path='system_architecture.png'):
    """创建AlgaeDiff-Net系统架构图"""

    # 设置画布
    fig, ax = plt.subplots(figsize=(14, 8))
    ax.set_xlim(0, 14)
    ax.set_ylim(0, 8)

    # 设置背景色
    ax.set_facecolor('#f9f9f9')

    # 定义颜色方案
    colors = {
        'backbone': '#3498db',  # 蓝色
        'lam': '#9b59b6',  # 紫色
        'lcm': '#2ecc71',  # 绿色
        'adem': '#e74c3c',  # 红色
        'diffusion': '#f39c12',  # 橙色
        'input': '#95a5a6',  # 灰色
        'output': '#34495e',  # 深蓝色
        'arrow': '#7f8c8d',  # 箭头颜色
    }

    # 绘制模型标题
    ax.text(7, 7.5, "AlgaeDiff-Net: Density-Aware Diffusion Network for Microalgae Detection",
            ha='center', fontsize=18, fontweight='bold')

    # 输入图像区域
    input_x, input_y = 1, 5
    input_width, input_height = 2, 1.5
    ax.add_patch(patches.Rectangle((input_x, input_y), input_width, input_height,
                                   edgecolor='black', facecolor=colors['input'], alpha=0.8))
    ax.text(input_x + input_width / 2, input_y + input_height / 2,
            "Input Image",
            ha='center', va='center', fontsize=12)

    # 主干网络
    backbone_x, backbone_y = 4, 5
    backbone_width, backbone_height = 2, 1.5
    ax.add_patch(patches.Rectangle((backbone_x, backbone_y), backbone_width, backbone_height,
                                   edgecolor='black', facecolor=colors['backbone'], alpha=0.8))
    ax.text(backbone_x + backbone_width / 2, backbone_y + backbone_height / 2,
            "Backbone\nFeature Extractor",
            ha='center', va='center', fontsize=12)

    # 输入到主干的箭头
    ax.annotate('', xy=(backbone_x, backbone_y + backbone_height / 2),
                xytext=(input_x + input_width, input_y + input_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 三个创新模块的输入位置
    module_y = backbone_y - 2.5

    # LAM模块
    lam_x, lam_y = 3, module_y
    lam_width, lam_height = 1.5, 1.2
    ax.add_patch(patches.Rectangle((lam_x, lam_y), lam_width, lam_height,
                                   edgecolor='black', facecolor=colors['lam'], alpha=0.8))
    ax.text(lam_x + lam_width / 2, lam_y + lam_height / 2,
            "Local Affinity\nModule (LAM)",
            ha='center', va='center', fontsize=10)

    # 主干到LAM的箭头
    ax.annotate('', xy=(lam_x + lam_width / 2, lam_y + lam_height),
                xytext=(backbone_x + backbone_width / 4, backbone_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # LCM模块
    lcm_x, lcm_y = 5, module_y
    lcm_width, lcm_height = 1.5, 1.2
    ax.add_patch(patches.Rectangle((lcm_x, lcm_y), lcm_width, lcm_height,
                                   edgecolor='black', facecolor=colors['lcm'], alpha=0.8))
    ax.text(lcm_x + lcm_width / 2, lcm_y + lcm_height / 2,
            "Local Cooperation\nModule (LCM)",
            ha='center', va='center', fontsize=10)

    # 主干到LCM的箭头
    ax.annotate('', xy=(lcm_x + lcm_width / 2, lcm_y + lcm_height),
                xytext=(backbone_x + backbone_width * 3 / 4, backbone_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # ADEM模块
    adem_x, adem_y = 7, module_y
    adem_width, adem_height = 1.5, 1.2
    ax.add_patch(patches.Rectangle((adem_x, adem_y), adem_width, adem_height,
                                   edgecolor='black', facecolor=colors['adem'], alpha=0.8))
    ax.text(adem_x + adem_width / 2, adem_y + adem_height / 2,
            "Auxiliary Density\nEstimation Module",
            ha='center', va='center', fontsize=10)

    # 主干到ADEM的箭头
    ax.annotate('', xy=(adem_x + adem_width / 2, adem_y + adem_height),
                xytext=(backbone_x + backbone_width, backbone_y + backbone_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 特征融合区
    fusion_x, fusion_y = 5.5, 3
    fusion_width, fusion_height = 2, 1
    ax.add_patch(patches.Rectangle((fusion_x, fusion_y), fusion_width, fusion_height,
                                   edgecolor='black', facecolor='#bdc3c7', alpha=0.8,
                                   linestyle='--'))
    ax.text(fusion_x + fusion_width / 2, fusion_y + fusion_height / 2,
            "Feature Fusion",
            ha='center', va='center', fontsize=12)

    # 各模块到融合区的箭头
    ax.annotate('', xy=(fusion_x + fusion_width / 2, fusion_y + fusion_height),
                xytext=(lam_x + lam_width / 2, lam_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    ax.annotate('', xy=(fusion_x + fusion_width / 2, fusion_y + fusion_height),
                xytext=(lcm_x + lcm_width / 2, lcm_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    ax.annotate('', xy=(fusion_x + fusion_width / 2, fusion_y + fusion_height),
                xytext=(adem_x + adem_width / 2, adem_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 条件扩散网络
    diffusion_x, diffusion_y = 8.5, 5
    diffusion_width, diffusion_height = 2.5, 1.5
    ax.add_patch(patches.Rectangle((diffusion_x, diffusion_y), diffusion_width, diffusion_height,
                                   edgecolor='black', facecolor=colors['diffusion'], alpha=0.8))
    ax.text(diffusion_x + diffusion_width / 2, diffusion_y + diffusion_height / 2,
            "Conditional Diffusion\nNetwork",
            ha='center', va='center', fontsize=12)

    # 主干到扩散的箭头
    ax.annotate('', xy=(diffusion_x, diffusion_y + diffusion_height / 2),
                xytext=(backbone_x + backbone_width, backbone_y + backbone_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 融合到扩散的箭头
    ax.annotate('', xy=(diffusion_x, diffusion_y),
                xytext=(fusion_x + fusion_width, fusion_y + fusion_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 输出检测结果
    output_x, output_y = 12, 5
    output_width, output_height = 1.5, 1.5
    ax.add_patch(patches.Rectangle((output_x, output_y), output_width, output_height,
                                   edgecolor='black', facecolor=colors['output'], alpha=0.8))
    ax.text(output_x + output_width / 2, output_y + output_height / 2,
            "Detection\nResults",
            ha='center', va='center', color='white', fontsize=12)

    # 扩散到输出的箭头
    ax.annotate('', xy=(output_x, output_y + output_height / 2),
                xytext=(diffusion_x + diffusion_width, diffusion_y + diffusion_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 添加时间步指示器
    timestep_x, timestep_y = diffusion_x + diffusion_width / 2, diffusion_y - 0.7
    radius = 0.4
    circle = plt.Circle((timestep_x, timestep_y), radius, color='#f39c12', alpha=0.6)
    ax.add_patch(circle)
    ax.text(timestep_x, timestep_y, "t", ha='center', va='center', fontsize=14, fontweight='bold')

    # 添加噪声箭头
    noise_x, noise_y = diffusion_x - 1, diffusion_y - 0.7
    ax.annotate('Noise', xy=(timestep_x - radius, timestep_y),
                xytext=(noise_x, noise_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5),
                fontsize=10)

    # 添加预测箭头
    pred_x, pred_y = diffusion_x + diffusion_width + 1, diffusion_y - 0.7
    ax.annotate('Prediction', xy=(timestep_x + radius, timestep_y),
                xytext=(pred_x, pred_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5),
                fontsize=10)

    # 模型创新点标注
    innovation_text = [
        "1. Local affinity enhancement for dense regions",
        "2. Multi-scale feature cooperation",
        "3. Density-aware detection with auxiliary estimation",
        "4. Adapted diffusion process for microalgae"
    ]

    for i, text in enumerate(innovation_text):
        ax.text(1, 1.8 - i * 0.4, text, fontsize=11)

    # 添加框架标题
    ax.add_patch(patches.Rectangle((0.8, 1.9), 8, 0.4,
                                   edgecolor=None, facecolor='#ecf0f1', alpha=0.8))
    ax.text(1, 2.15, "Key Innovations:", fontsize=12, fontweight='bold')

    # 关闭坐标轴
    ax.axis('off')

    plt.tight_layout()
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.show()


create_system_architecture()

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np


def create_lam_diagram(save_path='lam_module_diagram.png'):
    """创建局部亲和力模块(LAM)的结构图"""

    # 设置画布
    fig, ax = plt.subplots(figsize=(12, 7))
    ax.set_xlim(0, 12)
    ax.set_ylim(0, 7)

    # 定义颜色方案
    colors = {
        'input': '#3498db',  # 蓝色
        'process': '#9b59b6',  # 紫色
        'output': '#2ecc71',  # 绿色
        'attention': '#e74c3c',  # 红色
        'block': '#f39c12',  # 橙色
    }

    # 基础组件尺寸
    block_width = 1.5
    block_height = 0.8

    # 输入特征
    input_x, input_y = 1, 5
    ax.add_patch(patches.Rectangle((input_x, input_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['input'], alpha=0.8))
    ax.text(input_x + block_width / 2, input_y + block_height / 2,
            "Input Feature",
            ha='center', va='center', fontsize=10)

    # 局部亲和力计算
    affinity_x, affinity_y = 4, 5
    affinity_width, affinity_height = 2.5, 1.5
    ax.add_patch(patches.Rectangle((affinity_x, affinity_y), affinity_width, affinity_height,
                                   edgecolor='black', facecolor=colors['process'], alpha=0.8))

    # 输入到亲和力模块的箭头
    ax.annotate('', xy=(affinity_x, affinity_y + affinity_height / 2),
                xytext=(input_x + block_width, input_y + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 亲和力模块内部细节
    ax.text(affinity_x + affinity_width / 2, affinity_y + affinity_height - 0.3,
            "Local Affinity Computation",
            ha='center', va='center', fontsize=10, fontweight='bold')

    # 亲和力计算内部的小组件
    smaller_block_width = 0.8
    smaller_block_height = 0.5

    # 元素1 - 空间卷积
    ax.add_patch(patches.Rectangle((affinity_x + 0.3, affinity_y + 0.3),
                                   smaller_block_width, smaller_block_height,
                                   edgecolor='black', facecolor='white', alpha=0.8))
    ax.text(affinity_x + 0.3 + smaller_block_width / 2, affinity_y + 0.3 + smaller_block_height / 2,
            "3x3 Conv",
            ha='center', va='center', fontsize=8)

    # 元素2 - 自注意力
    ax.add_patch(patches.Rectangle((affinity_x + affinity_width - smaller_block_width - 0.3,
                                    affinity_y + 0.3),
                                   smaller_block_width, smaller_block_height,
                                   edgecolor='black', facecolor='white', alpha=0.8))
    ax.text(affinity_x + affinity_width - 0.3 - smaller_block_width / 2,
            affinity_y + 0.3 + smaller_block_height / 2,
            "Self-Attention",
            ha='center', va='center', fontsize=8)

    # 亲和度矩阵
    affinity_matrix_x, affinity_matrix_y = 3.5, 3
    affinity_matrix_width = 1.5
    affinity_matrix_height = 1.5

    # 矩阵表示
    grid_size = 5
    cell_size = min(affinity_matrix_width, affinity_matrix_height) / grid_size

    # 绘制亲和度矩阵网格
    for i in range(grid_size):
        for j in range(grid_size):
            # 根据位置计算亲和度强度（仅作可视化用）
            # 距离对角线越近，亲和力越大
            affinity = 1 - min(abs(i - j), abs(grid_size - 1 - i - j)) / (grid_size / 2)
            color_val = 1 - 0.8 * affinity

            ax.add_patch(patches.Rectangle(
                (affinity_matrix_x + j * cell_size,
                 affinity_matrix_y + i * cell_size),
                cell_size, cell_size,
                edgecolor='black',
                facecolor=(color_val, color_val, color_val),
                linewidth=0.5))

    # 亲和度矩阵标签
    ax.text(affinity_matrix_x + affinity_matrix_width / 2,
            affinity_matrix_y - 0.3,
            "Affinity Matrix",
            ha='center', va='center', fontsize=10)

    # 亲和力计算到亲和度矩阵的箭头
    ax.annotate('', xy=(affinity_matrix_x + affinity_matrix_width / 2,
                        affinity_matrix_y + affinity_matrix_height),
                xytext=(affinity_x + 1, affinity_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 局部注意力门控
    gate_x, gate_y = 6, 3
    gate_width, gate_height = 1.5, 1.5

    # 绘制门控符号（一个带有σ的圆）
    circle = plt.Circle((gate_x + gate_width / 2, gate_y + gate_height / 2),
                        min(gate_width, gate_height) / 2,
                        facecolor=colors['attention'], alpha=0.8, edgecolor='black')
    ax.add_patch(circle)
    ax.text(gate_x + gate_width / 2, gate_y + gate_height / 2,
            "σ",
            ha='center', va='center', fontsize=14, fontweight='bold')

    # 门控标签
    ax.text(gate_x + gate_width / 2, gate_y - 0.3,
            "Attention Gate",
            ha='center', va='center', fontsize=10)

    # 亲和度矩阵到门控的箭头
    ax.annotate('', xy=(gate_x, gate_y + gate_height / 2),
                xytext=(affinity_matrix_x + affinity_matrix_width,
                        affinity_matrix_y + affinity_matrix_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 亲和力计算到门控的箭头
    ax.annotate('', xy=(gate_x + gate_width / 2, gate_y + gate_height),
                xytext=(affinity_x + affinity_width, affinity_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 特征增强
    enhance_x, enhance_y = 8.5, 5
    enhance_width, enhance_height = 2, 1.2
    ax.add_patch(patches.Rectangle((enhance_x, enhance_y), enhance_width, enhance_height,
                                   edgecolor='black', facecolor=colors['block'], alpha=0.8))
    ax.text(enhance_x + enhance_width / 2, enhance_y + enhance_height / 2,
            "Feature Enhancement\nwith Local Context",
            ha='center', va='center', fontsize=10)

    # 门控到特征增强的箭头
    ax.annotate('', xy=(enhance_x, enhance_y + enhance_height / 2),
                xytext=(gate_x + gate_width, gate_y + gate_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 亲和力计算到特征增强的箭头
    ax.annotate('', xy=(enhance_x, enhance_y + enhance_height / 2),
                xytext=(affinity_x + affinity_width, affinity_y + affinity_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 输出特征
    output_x, output_y = 11, 5
    ax.add_patch(patches.Rectangle((output_x, output_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['output'], alpha=0.8))
    ax.text(output_x + block_width / 2, output_y + block_height / 2,
            "Enhanced\nFeature",
            ha='center', va='center', fontsize=10)

    # 特征增强到输出的箭头
    ax.annotate('', xy=(output_x, output_y + block_height / 2),
                xytext=(enhance_x + enhance_width, enhance_y + enhance_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 添加公式标注
    formula_y = 1.8
    ax.text(2, formula_y, r"Affinity Matrix: $A_{ij} = \frac{f(x_i)^T \cdot g(x_j)}{\sqrt{d}}$", fontsize=11)
    ax.text(2, formula_y - 0.5, r"Attention Gate: $G = \sigma(W_g \cdot A + b_g)$", fontsize=11)
    ax.text(2, formula_y - 1.0, r"Enhanced Feature: $F_{out} = F_{in} + G \odot (W_e \cdot F_{in})$", fontsize=11)

    # 添加模块标题
    ax.text(6, 7.5, "Local Affinity Module (LAM)",
            ha='center', fontsize=14, fontweight='bold')

    # 添加模块说明
    ax.text(6, 7.0, "Enhances feature representation by capturing local context dependencies",
            ha='center', fontsize=11, style='italic')

    # 区域高亮 - 密集区域检测增强
    highlight_x, highlight_y = 3, 3
    highlight_width, highlight_height = 5, 1.5
    ax.add_patch(patches.Rectangle((highlight_x, highlight_y), highlight_width, highlight_height,
                                   edgecolor='#e74c3c', facecolor='none', alpha=0.8,
                                   linestyle='--', linewidth=2))

    ax.text(highlight_x + highlight_width / 2+1, highlight_y - 0.2,
            "Benefits for Dense Microalgae Regions",
            ha='center', va='center', fontsize=10, color='#e74c3c')

    # 关闭坐标轴
    ax.axis('off')

    plt.tight_layout()
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.show()


create_lam_diagram()
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np


# def create_lcm_diagram(save_path='lcm_module_diagram.png'):
#     """创建局部协作模块(LCM)的结构图"""
#
#     # 设置画布
#     fig, ax = plt.subplots(figsize=(12, 8))
#     ax.set_xlim(0, 12)
#     ax.set_ylim(0, 8)
#
#     # 定义颜色方案
#     colors = {
#         'input': '#3498db',  # 蓝色
#         'process': '#2ecc71',  # 绿色
#         'fusion': '#9b59b6',  # 紫色
#         'output': '#e74c3c',  # 红色
#         'block': '#f39c12',  # 橙色
#     }
#
#     # 基础组件尺寸
#     block_width = 1.6
#     block_height = 0.8
#
#     # 绘制多尺度特征输入
#     # P3-P7特征
#     feature_ys = {
#         'P3': 6.5,
#         'P4': 5.5,
#         'P5': 4.5,
#         'P6': 3.5,
#         'P7': 2.5
#     }
#
#     input_x = 1
#
#     # 绘制输入特征块
#     for feature, y in feature_ys.items():
#         ax.add_patch(patches.Rectangle((input_x, y), block_width, block_height,
#                                        edgecolor='black', facecolor=colors['input'], alpha=0.8))
#         ax.text(input_x + block_width / 2, y + block_height / 2,
#                 f"{feature} Feature",
#                 ha='center', va='center', fontsize=10)
#
#     # 局部信息增强
#     process_x = 4
#     process_width = 2.5
#     process_height = 1.0
#
#     for feature, y in feature_ys.items():
#         # 处理模块
#         ax.add_patch(patches.Rectangle((process_x, y - 0.1), process_width, process_height,
#                                        edgecolor='black', facecolor=colors['process'], alpha=0.8))
#
#         # 根据特征级别设置不同的处理函数
#         if feature in ['P3', 'P4']:
#             process_name = "Local Detail\nEnhancement"
#         elif feature == 'P5':
#             process_name = "Context\nIntegration"
#         else:
#             process_name = "Global Context\nModeling"
#
#         ax.text(process_x + process_width / 2, y - 0.1 + process_height / 2,
#                 process_name,
#                 ha='center', va='center', fontsize=9)
#
#         # 输入到处理的箭头
#         ax.annotate('', xy=(process_x, y - 0.1 + process_height / 2),
#                     xytext=(input_x + block_width, y + block_height / 2),
#                     arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
#
#     # 特征交互与融合
#     fusion_x = 8
#     fusion_y = 4.5
#     fusion_width = 2.5
#     fusion_height = 2.5
#
#     # 融合模块
#     ax.add_patch(patches.Rectangle((fusion_x, fusion_y - fusion_height / 2),
#                                    fusion_width, fusion_height,
#                                    edgecolor='black', facecolor=colors['fusion'], alpha=0.8))
#
#     # 融合模块中心点
#     fusion_center_x = fusion_x + fusion_width / 2
#     fusion_center_y = fusion_y
#
#     # 融合模块标题
#     ax.text(fusion_center_x, fusion_center_y + 0.8,
#             "Feature Cooperation",
#             ha='center', va='center', fontsize=11, fontweight='bold')
#
#     # 融合模块内部的小组件
#     smaller_block_width = 1.0
#     smaller_block_height = 0.5
#
#     # 跨尺度注意力
#     ax.add_patch(patches.Rectangle((fusion_center_x - smaller_block_width / 2,
#                                     fusion_center_y + 0.2),
#                                    # 跨尺度注意力
#                                    ax.add_patch(patches.Rectangle((fusion_center_x - smaller_block_width / 2,
#                                                                    fusion_center_y + 0.2),
#                                                                   smaller_block_width, smaller_block_height,
#                                                                   edgecolor='black', facecolor='white', alpha=0.8))
#     ax.text(fusion_center_x, fusion_center_y + 0.2 + smaller_block_height / 2,
#             "Cross-scale\nAttention",
#             ha='center', va='center', fontsize=8)
#
#     # 自适应加权
#     ax.add_patch(patches.Rectangle((fusion_center_x - smaller_block_width / 2,
#                                     fusion_center_y - 0.4),
#                                    smaller_block_width, smaller_block_height,
#                                    edgecolor='black', facecolor='white', alpha=0.8))
#     ax.text(fusion_center_x, fusion_center_y - 0.4 + smaller_block_height / 2,
#             "Adaptive\nWeighting",
#             ha='center', va='center', fontsize=8)
#
#     # 从处理模块到融合模块的箭头
#     for feature, y in feature_ys.items():
#         ax.annotate('', xy=(fusion_x, fusion_center_y),
#                     xytext=(process_x + process_width, y - 0.1 + process_height / 2),
#                     arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
#
#     # 输出特征
#     output_x = 11
#     output_ys = {
#         'P3': 6.5,
#         'P4': 5.5,
#         'P5': 4.5,
#         'P6': 3.5,
#         'P7': 2.5
#     }
#
#     # 绘制输出特征块
#     for feature, y in output_ys.items():
#         ax.add_patch(patches.Rectangle((output_x, y), block_width, block_height,
#                                        edgecolor='black', facecolor=colors['output'], alpha=0.8))
#     ax.text(output_x + block_width / 2, y + block_height / 2,
#             f"Enhanced {feature}",
#             ha='center', va='center', fontsize=10)
#
#     # 融合到输出的箭头
#     ax.annotate('', xy=(output_x, y + block_height / 2),
#                 xytext=(fusion_x + fusion_width, fusion_center_y),
#                 arrowprops=dict(arrowstyle='->', color='black', lw=1.5))
#
#     # 添加特征互补性强调区域
#     complementary_x = 7
#     complementary_y = 1.5
#     complementary_width = 4
#     complementary_height = 0.8
#
#     ax.add_patch(patches.Rectangle((complementary_x, complementary_y),
#                                    complementary_width, complementary_height,
#                                    edgecolor='black', facecolor='#ecf0f1', alpha=0.8))
#     ax.text(complementary_x + complementary_width / 2, complementary_y + complementary_height / 2,
#             "Feature Complementarity Enhancement",
#             ha='center', va='center', fontsize=10)
#
#     # 从融合模块到特征互补性区域的箭头
#     ax.annotate('', xy=(complementary_x + complementary_width / 2, complementary_y),
#                 xytext=(fusion_center_x, fusion_center_y - fusion_height / 2),
#                 arrowprops=dict(arrowstyle='->', color='black', linestyle='--', lw=1.5))
#
#     # 添加模块标题
#     ax.text(6, 7.5, "Local Cooperation Module (LCM)",
#             ha='center', fontsize=14, fontweight='bold')
#
#     # 添加模块说明
#     ax.text(6, 7.0, "Facilitates cooperation between multi-scale feature maps",
#             ha='center', fontsize=11, style='italic')
#
#     # 添加跨尺度交互说明
#     explanation_text = [
#         "P3-P4: Fine-grained details and local features",
#         "P5: Intermediate context integration",
#         "P6-P7: Global context and large-scale patterns"
#     ]
#
#     for i, text in enumerate(explanation_text):
#         ax.text(1.5, 1.5 - i * 0.3, text, fontsize=9)
#
#     # 关闭坐标轴
#     ax.axis('off')
#
#     plt.tight_layout()
#     plt.savefig(save_path, dpi=300, bbox_inches='tight')
#     plt.show()
#
#     create_lcm_diagram()
#
#     import matplotlib.pyplot as plt
#     import matplotlib.patches as patches
#     import numpy as np


def create_adem_diagram(save_path='adem_module_diagram.png'):
    """创建辅助密度估计模块(ADEM)的结构图"""

    # 设置画布
    fig, ax = plt.subplots(figsize=(14, 8))
    ax.set_xlim(0, 14)
    ax.set_ylim(0, 8)

    # 定义颜色方案
    colors = {
        'input': '#3498db',  # 蓝色
        'process': '#2ecc71',  # 绿色
        'density': '#9b59b6',  # 紫色
        'fusion': '#e74c3c',  # 红色
        'block': '#f39c12',  # 橙色
        'backbone': '#1abc9c',  # 青色
    }

    # 添加模块标题
    ax.text(7, 7.5, "Auxiliary Density Estimation Module (ADEM)",
            ha='center', fontsize=14, fontweight='bold')

    # 添加模块说明
    ax.text(7, 7.0, "Estimates density maps to guide detection in crowded regions",
            ha='center', fontsize=11, style='italic')

    # 基础组件尺寸
    block_width = 1.8
    block_height = 0.8

    # 输入特征
    input_x, input_y = 1, 5.5
    ax.add_patch(patches.Rectangle((input_x, input_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['input'], alpha=0.8))
    ax.text(input_x + block_width / 2, input_y + block_height / 2,
            "Backbone Features",
            ha='center', va='center', fontsize=10)

    # 图像输入
    img_input_x, img_input_y = 1, 4
    ax.add_patch(patches.Rectangle((img_input_x, img_input_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['backbone'], alpha=0.8))
    ax.text(img_input_x + block_width / 2, img_input_y + block_height / 2,
            "Input Image",
            ha='center', va='center', fontsize=10)

    # 特征处理编码器
    encoder_x, encoder_y = 4, 5.5
    encoder_width, encoder_height = 2.5, 1.5
    ax.add_patch(patches.Rectangle((encoder_x, encoder_y), encoder_width, encoder_height,
                                   edgecolor='black', facecolor=colors['process'], alpha=0.8))

    # 编码器内部细节
    ax.text(encoder_x + encoder_width / 2, encoder_y + encoder_height - 0.3,
            "Feature Encoder",
            ha='center', va='center', fontsize=11, fontweight='bold')

    # 编码器内部的小组件
    smaller_block_width = 1.0
    smaller_block_height = 0.5

    # 卷积层
    ax.add_patch(patches.Rectangle((encoder_x + 0.75, encoder_y + 0.5),
                                   smaller_block_width, smaller_block_height,
                                   edgecolor='black', facecolor='white', alpha=0.8))
    ax.text(encoder_x + 0.75 + smaller_block_width / 2, encoder_y + 0.5 + smaller_block_height / 2,
            "Conv Layers",
            ha='center', va='center', fontsize=8)

    # 输入到编码器的箭头
    ax.annotate('', xy=(encoder_x, encoder_y + encoder_height / 2),
                xytext=(input_x + block_width, input_y + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 图像到编码器的箭头
    ax.annotate('', xy=(encoder_x, encoder_y),
                xytext=(img_input_x + block_width, img_input_y + block_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 密度解码器
    decoder_x, decoder_y = 7.5, 5.5
    decoder_width, decoder_height = 2.5, 1.5
    ax.add_patch(patches.Rectangle((decoder_x, decoder_y), decoder_width, decoder_height,
                                   edgecolor='black', facecolor=colors['density'], alpha=0.8))

    # 解码器内部细节
    ax.text(decoder_x + decoder_width / 2, decoder_y + decoder_height - 0.3,
            "Density Decoder",
            ha='center', va='center', fontsize=11, fontweight='bold')

    # 解码器内部的小组件
    ax.add_patch(patches.Rectangle((decoder_x + 0.75, decoder_y + 0.5),
                                   smaller_block_width, smaller_block_height,
                                   edgecolor='black', facecolor='white', alpha=0.8))
    ax.text(decoder_x + 0.75 + smaller_block_width / 2, decoder_y + 0.5 + smaller_block_height / 2,
            "Deconv Layers",
            ha='center', va='center', fontsize=8)

    # 编码器到解码器的箭头
    ax.annotate('', xy=(decoder_x, decoder_y + decoder_height / 2),
                xytext=(encoder_x + encoder_width, encoder_y + encoder_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 密度图输出
    density_map_x, density_map_y = 11, 5.5
    ax.add_patch(patches.Rectangle((density_map_x, density_map_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['density'], alpha=0.8))
    ax.text(density_map_x + block_width / 2, density_map_y + block_height / 2,
            "Density Map",
            ha='center', va='center', fontsize=10)

    # 解码器到密度图的箭头
    ax.annotate('', xy=(density_map_x, density_map_y + block_height / 2),
                xytext=(decoder_x + decoder_width, decoder_y + decoder_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 密度指导特征增强
    enhancement_x, enhancement_y = 7.5, 3
    enhancement_width, enhancement_height = 2.5, 1.5
    ax.add_patch(patches.Rectangle((enhancement_x, enhancement_y), enhancement_width, enhancement_height,
                                   edgecolor='black', facecolor=colors['fusion'], alpha=0.8))

    # 特征增强内部细节
    ax.text(enhancement_x + enhancement_width / 2, enhancement_y + enhancement_height - 0.3,
            "Density-Guided\nFeature Enhancement",
            ha='center', va='center', fontsize=11, fontweight='bold')

    # 密度图到特征增强的箭头
    ax.annotate('', xy=(enhancement_x + enhancement_width / 2, enhancement_y + enhancement_height),
                xytext=(decoder_x + decoder_width / 2, decoder_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 编码器到特征增强的箭头
    ax.annotate('', xy=(enhancement_x, enhancement_y + enhancement_height / 2),
                xytext=(encoder_x + encoder_width / 2, encoder_y),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 增强后特征输出
    enhanced_feature_x, enhanced_feature_y = 11, 3
    ax.add_patch(patches.Rectangle((enhanced_feature_x, enhanced_feature_y), block_width, block_height,
                                   edgecolor='black', facecolor=colors['block'], alpha=0.8))
    ax.text(enhanced_feature_x + block_width / 2, enhanced_feature_y + block_height / 2,
            "Density-Aware\nFeatures",
            ha='center', va='center', fontsize=10)

    # 特征增强到增强后特征的箭头
    ax.annotate('', xy=(enhanced_feature_x, enhanced_feature_y + block_height / 2),
                xytext=(enhancement_x + enhancement_width, enhancement_y + enhancement_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', lw=1.5))

    # 添加密度监督训练块
    supervision_x, supervision_y = 11, 4.5
    supervision_width, supervision_height = 1

    ax.add_patch(patches.Rectangle((density_map_x + block_width / 2 - supervision_width / 2,
                                    supervision_y),
                                   supervision_width, supervision_height,
                                   edgecolor='black', facecolor='#bdc3c7', alpha=0.8,
                                   linestyle='--'))

    ax.text(density_map_x + block_width / 2, supervision_y + supervision_height / 2,
            "Density\nLoss",
            ha='center', va='center', fontsize=9)

    # 密度图到监督的箭头
    ax.annotate('', xy=(density_map_x + block_width / 2, supervision_y + supervision_height),
                xytext=(density_map_x + block_width / 2, density_map_y),
                arrowprops=dict(arrowstyle='->', color='black', linestyle='--', lw=1.5))

    # 添加密度图可视化示例
    heatmap_x, heatmap_y = 11, 1.5
    heatmap_width, heatmap_height = 2, 1

    # 创建网格数据
    X, Y = np.meshgrid(np.linspace(0, 1, 20), np.linspace(0, 1, 10))
    # 创建高斯峰值作为密度图可视化
    Z = np.exp(-((X - 0.7) ** 2 + (Y - 0.5) ** 2) / 0.05) + 0.5 * np.exp(-((X - 0.3) ** 2 + (Y - 0.6) ** 2) / 0.1)

    # 绘制热力图
    heatmap = ax.pcolormesh(
        X + heatmap_x,
        Y + heatmap_y,
        Z,
        cmap='viridis',
        alpha=0.8,
        shading='auto'
    )

    # 添加热力图边框
    ax.add_patch(patches.Rectangle((heatmap_x, heatmap_y),
                                   heatmap_width, heatmap_height,
                                   edgecolor='black', facecolor='none', lw=1))

    # 添加热力图标签
    ax.text(heatmap_x + heatmap_width / 2, heatmap_y - 0.2,
            "Density Map Visualization",
            ha='center', va='center', fontsize=9)

    # 添加密集区域检测改进说明
    explanation_x, explanation_y = 2, 2.5
    explanation_width, explanation_height = 4, 1.5

    ax.add_patch(patches.Rectangle((explanation_x, explanation_y),
                                   explanation_width, explanation_height,
                                   edgecolor='black', facecolor='#ecf0f1', alpha=0.8))

    explanation_text = [
        "Advantages:",
        "1. Better detection in crowded regions",
        "2. Improved small object localization",
        "3. Density-aware feature attention",
        "4. Alleviates occlusion challenges"
    ]

    for i, text in enumerate(explanation_text):
        ax.text(explanation_x + 0.2, explanation_y + explanation_height - 0.3 - i * 0.25,
                text, fontsize=9, ha='left')

    # 连接线 - 从增强特征到说明区域
    ax.annotate('', xy=(explanation_x + explanation_width, explanation_y + explanation_height / 2),
                xytext=(enhancement_x, enhancement_y + enhancement_height / 2),
                arrowprops=dict(arrowstyle='->', color='black', linestyle='--', lw=1.5))

    # 关闭坐标轴
    ax.axis('off')

    plt.tight_layout()
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.show()


# create_adem_diagram()

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
from matplotlib.colors import LinearSegmentedColormap


def create_diffusion_principle_diagram(save_path='diffusion_principle.png'):
    """创建条件扩散网络在微藻检测中的工作原理图"""

    # 设置画布
    fig, ax = plt.subplots(figsize=(14, 8))
    ax.set_xlim(0, 14)
    ax.set_ylim(0, 8)

    # 定义颜色方案
    colors = {
        'noise': '#3498db',  # 蓝色
        'image': '#2ecc71',  # 绿色
        'output': '#e74c3c',  # 红色
        'condition': '#9b59b6',  # 紫色
        'model': '#f39c12',  # 橙色
        'arrow': '#7f8c8d',  # 灰色
        'arrow_highlight': '#c0392b',  # 深红色
    }

    # 添加标题
    ax.text(7, 7.5, "Conditional Diffusion Network for Microalgae Detection",
            ha='center', fontsize=16, fontweight='bold')

    # 添加说明文本
    ax.text(7, 7.0, "Denoising process guided by feature conditions from backbone network",
            ha='center', fontsize=12, style='italic')

    # 绘制扩散时间步骤轴
    arrow_length = 10
    timestep_y = 6
    ax.arrow(2, timestep_y, arrow_length, 0,
             head_width=0.2, head_length=0.3, fc=colors['arrow'], ec=colors['arrow'])

    # 添加时间步标签
    ax.text(2, timestep_y + 0.3, "t = T (Noise)", ha='center', fontsize=12)
    ax.text(12, timestep_y + 0.3, "t = 0 (Prediction)", ha='center', fontsize=12)
    ax.text(7, timestep_y + 0.3, "Denoising Process", ha='center', fontsize=12)

    # 扩散步骤示例 - 状态转变
    num_steps = 5
    step_width = arrow_length / (num_steps - 1)
    boxes_y = 4.5
    box_size = 1.0

    # 为从纯噪声到清晰检测结果的过渡创建颜色映射
    noise_to_detection_colors = [(0.5, 0.5, 0.5), (0.3, 0.5, 0.8), (0.1, 0.6, 0.9), (0, 0.7, 0.7), (0, 0.8, 0.4)]

    # 绘制步骤框和箭头
    for i in range(num_steps):
        x = 2 + i * step_width

        # 绘制框
        box = patches.Rectangle((x - box_size / 2, boxes_y - box_size / 2),
                                box_size, box_size,
                                edgecolor='black', facecolor=noise_to_detection_colors[i],
                                alpha=0.7)
        ax.add_patch(box)

        # 添加时间步标签
        timestep_text = f"t = {int((num_steps - 1 - i) * 1000 / (num_steps - 1))}"
        ax.text(x, boxes_y - box_size / 2 - 0.2, timestep_text, ha='center', fontsize=10)

        # 绘制连接箭头 (除最后一个步骤外)
        if i < num_steps - 1:
            next_x = x + step_width
            arrow_length = next_x - x - box_size
            ax.arrow(x + box_size / 2, boxes_y, arrow_length, 0,
                     head_width=0.15, head_length=0.1, fc=colors['arrow'], ec=colors['arrow'])

    # 绘制步骤内部的检测框
    # 第一个框 (纯噪声)
    ax.text(2, boxes_y, "?", ha='center', va='center', fontsize=20, color='white')

    # 中间步骤 (渐进清晰的检测框)
    for i in range(1, num_steps - 1):
        x = 2 + i * step_width
        # 根据进度调整透明度和位置精确度
        alpha = 0.3 + i * 0.2
        jitter = 0.2 * (num_steps - 1 - i) / (num_steps - 2)

        # 添加逐渐清晰的检测框
        detection_box = patches.Rectangle((x - 0.3 - jitter / 2, boxes_y - 0.2 - jitter / 2),
                                          0.6 + jitter, 0.4 + jitter,
                                          edgecolor='white', facecolor='none',
                                          alpha=alpha, linewidth=1.5)
        ax.add_patch(detection_box)

    # 最后一个框 (清晰的检测结果)
    final_x = 2 + (num_steps - 1) * step_width
    detection_box = patches.Rectangle((final_x - 0.3, boxes_y - 0.2),
                                      0.6, 0.4,
                                      edgecolor='white', facecolor='none',
                                      alpha=1.0, linewidth=2)
    ax.add_patch(detection_box)

    # 添加条件特征
    condition_y = 3
    condition_x = 7
    condition_width = 3
    condition_height = 1

    # 条件特征框
    condition_box = patches.Rectangle((condition_x - condition_width / 2, condition_y - condition_height / 2),
                                      condition_width, condition_height,
                                      edgecolor='black', facecolor=colors['condition'],
                                      alpha=0.8)
    ax.add_patch(condition_box)

    ax.text(condition_x, condition_y, "Feature Conditions",
            ha='center', va='center', fontsize=12)

    # 添加从条件到各扩散步骤的连接
    for i in range(1, num_steps):
        x = 2 + i * step_width
        ax.plot([condition_x, x], [condition_y, boxes_y - box_size / 2],
                '--', color=colors['arrow_highlight'], alpha=0.5 + i * 0.1, linewidth=1)

    # 添加原始图像示意
    image_y = 1.5
    image_x = 3
    image_size = 1.2

    # 图像框
    image_box = patches.Rectangle((image_x - image_size / 2, image_y - image_size / 2),
                                  image_size, image_size,
                                  edgecolor='black', facecolor=colors['image'],
                                  alpha=0.8)
    ax.add_patch(image_box)

    # 在图像框中绘制简单的藻类示意图
    # 创建一个小的示例图像
    # 在创建示例图像的部分修改为：
    algae_img = np.ones((20, 20, 3))

    for _ in range(8):
        x = np.random.randint(3, 17)
        y = np.random.randint(3, 17)
        r = np.random.randint(2, 4)

        # 生成坐标网格
        y_coords = np.arange(-r, r + 1)
        x_coords = np.arange(-r, r + 1)
        rr, cc = np.meshgrid(y_coords, x_coords, indexing='ij')

        # 创建圆形掩码
        circle = (rr ** 2 + cc ** 2) <= r ** 2

        # 获取有效坐标
        valid_y = y + rr[circle]
        valid_x = x + cc[circle]

        # 确保坐标在图像范围内
        valid_mask = (valid_y >= 0) & (valid_y < 20) & (valid_x >= 0) & (valid_x < 20)
        valid_y = valid_y[valid_mask]
        valid_x = valid_x[valid_mask]

        # 绘制微藻
        algae_img[valid_y, valid_x] = [0.2, 0.7, 0.3]

    # 显示图像
    ax.imshow(algae_img, extent=[image_x - image_size / 2, image_x + image_size / 2,
                                 image_y - image_size / 2, image_y + image_size / 2])

    # 添加图像标签
    ax.text(image_x, image_y - image_size / 2 - 0.2, "Input Image",
            ha='center', fontsize=11)

    # 连接图像到条件特征
    ax.plot([image_x, condition_x - condition_width / 2], [image_y, condition_y],
            '->', color=colors['arrow_highlight'], linewidth=1.5)

    # 添加最终检测结果
    result_y = 1.5
    result_x = 11
    result_size = 1.2

    # 结果框
    result_box = patches.Rectangle((result_x - result_size / 2, result_y - result_size / 2),
                                   result_size, result_size,
                                   edgecolor='black', facecolor=colors['output'],
                                   alpha=0.8)
    ax.add_patch(result_box)

    # 在结果框中绘制带有边界框的微藻检测结果
    # 使用相同的基础图像
    result_img = algae_img.copy()

    # 添加检测框
    for i in range(8):
        x = np.random.randint(3, 17)
        y = np.random.randint(3, 17)
        w = np.random.randint(3, 5)
        h = np.random.randint(3, 5)

        # 确保在图像边界内
        x1 = max(0, x - w // 2)
        y1 = max(0, y - h // 2)
        x2 = min(19, x + w // 2)
        y2 = min(19, y + h // 2)

        # 画矩形边框
        result_img[y1, x1:x2 + 1] = [1, 1, 1]  # 白色边框
        result_img[y2, x1:x2 + 1] = [1, 1, 1]
        result_img[y1:y2 + 1, x1] = [1, 1, 1]
        result_img[y1:y2 + 1, x2] = [1, 1, 1]

    # 显示结果图像
    ax.imshow(result_img, extent=[result_x - result_size / 2, result_x + result_size / 2,
                                  result_y - result_size / 2, result_y + result_size / 2])

    # 添加结果标签
    ax.text(result_x, result_y - result_size / 2 - 0.2, "Detection Result",
            ha='center', fontsize=11)

    # 连接最终扩散步骤到结果
    ax.plot([final_x, result_x], [boxes_y, result_y + result_size / 2],
            '->', color=colors['arrow_highlight'], linewidth=1.5)

    # 添加扩散过程的数学描述
    math_x = 7
    math_y = 2.3

    math_text = [
        r"Forward Process: $q(x_t | x_{t-1}) = \mathcal{N}(x_t; \sqrt{1-\beta_t}x_{t-1}, \beta_t\mathbf{I})$",
        r"Reverse Process: $p_\theta(x_{t-1} | x_t, c) = \mathcal{N}(x_{t-1}; \mu_\theta(x_t, t, c), \Sigma_\theta(x_t, t))$"
    ]

    for i, text in enumerate(math_text):
        ax.text(math_x, math_y - i * 0.5, text, ha='center', fontsize=11)

    # 添加创新点说明
    innovation_x = 11
    innovation_y = 3
    innovation_width = 2.5
    innovation_height = 1.5

    innovation_box = patches.Rectangle((innovation_x - innovation_width / 2, innovation_y - innovation_height / 2),
                                       innovation_width, innovation_height,
                                       edgecolor='black', facecolor='#ecf0f1',
                                       alpha=0.8, linestyle='--')
    ax.add_patch(innovation_box)

    innovation_text = [
        "AlgaeDiff-Net Innovations:",
        "1. Density-aware conditioning",
        "2. Adaptive noise scheduling",
        "3. Multi-scale feature integration"
    ]

    for i, text in enumerate(innovation_text):
        ax.text(innovation_x - innovation_width / 2 + 0.2,
                innovation_y + innovation_height / 2 - 0.3 - i * 0.3,
                text, fontsize=9, ha='left')

    # 关闭坐标轴
    ax.axis('off')

    plt.tight_layout()
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.show()


create_diffusion_principle_diagram()

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np


def create_multiscale_feature_fusion(save_path='multiscale_feature_fusion.png'):
    """创建多尺度特征融合与密度信息结合的示意图"""

    # 设置画布
    fig, ax = plt.subplots(figsize=(12, 8))
    ax.set_xlim(0, 12)
    ax.set_ylim(0, 8)

    # 定义颜色方案
    colors = {
        'backbone': '#3498db',  # 蓝色
        'density': '#9b59b6',  # 紫色
        'feature': '#2ecc71',  # 绿色
        'fusion': '#e74c3c',  # 红色
        'output': '#f39c12',  # 橙色
    }

    # 添加标题
    ax.text(6, 7.5, "Multi-scale Feature Fusion with Density Information",
            ha='center', fontsize=14, fontweight='bold')

    # 添加说明
    ax.text(6, 7.0, "Integration of feature maps at different scales with density awareness",
            ha='center', fontsize=11, style='italic')

    # 绘制基本网络结构
    # 主干网络特征
    backbone_x = 2
    backbone_y = 5
    backbone_width = 1.5
    backbone_height = 1.5

    backbone_box = patches.Rectangle((backbone_x - backbone_width / 2, backbone_y - backbone_height / 2),
                                     backbone_width, backbone_height,
                                     edgecolor='black', facecolor=colors['backbone'],
                                     alpha=0.8)
    ax.add_patch(backbone_box)

    ax.text(backbone_x, backbone_y, "Backbone\nFeatures",
            ha='center', va='center', fontsize=11)

    # 多尺度特征
    feature_levels = ['P3', 'P4', 'P5', 'P6', 'P7']
    feature_x = 4
    feature_ys = [6, 5.5, 5, 4.5, 4]
    feature_width = 1.2
    feature_height = 0.6

    # 绘制特征级别
    for i, (level, y) in enumerate(zip(feature_levels, feature_ys)):
        # 不同深度的颜色
        alpha = 0.6 + 0.08 * i

        feature_box = patches.Rectangle((feature_x - feature_width / 2, y - feature_height / 2),
                                        feature_width, feature_height,
                                        edgecolor='black', facecolor=colors['feature'],
                                        alpha=alpha)
        ax.add_patch(feature_box)

        ax.text(feature_x, y, f"{level}",
                ha='center', va='center', fontsize=10)

        # 连接主干到特征级别
        ax.plot([backbone_x + backbone_width / 2, feature_x - feature_width / 2],
                [backbone_y, y],
                '-', color='black', linewidth=1)

    # 密度估计模块
    density_x = 2
    density_y = 2.5
    density_width = 1.5
    density_height = 1

    density_box = patches.Rectangle((density_x - density_width / 2, density_y - density_height / 2),
                                    density_width, density_height,
                                    edgecolor='black', facecolor=colors['density'],
                                    alpha=0.8)
    ax.add_patch(density_box)

    ax.text(density_x, density_y, "Density\nEstimation",
            ha='center', va='center', fontsize=10)

    # 连接主干到密度估计
    ax.plot([backbone_x, density_x],
            [backbone_y - backbone_height / 2, density_y + density_height / 2],
            '-', color='black', linewidth=1)

    # 密度热力图
    heatmap_x = 4
    heatmap_y = 2.5
    heatmap_width = 1.5
    heatmap_height = 1

    # 创建密度热力图
    X, Y = np.meshgrid(np.linspace(0, 1, 20), np.linspace(0, 1, 10))
    Z = np.exp(-((X - 0.3) ** 2 + (Y - 0.5) ** 2) / 0.05) + 0.7 * np.exp(-((X - 0.7) ** 2 + (Y - 0.6) ** 2) / 0.1)

    # 绘制热力图
    heatmap = ax.pcolormesh(
        X * heatmap_width + (heatmap_x - heatmap_width / 2),
        Y * heatmap_height + (heatmap_y - heatmap_height / 2),
        Z,
        cmap='viridis',
        alpha=0.8,
        shading='auto'
    )

    # 添加热力图边框
    ax.add_patch(patches.Rectangle((heatmap_x - heatmap_width / 2, heatmap_y - heatmap_height / 2),
                                   heatmap_width, heatmap_height,
                                   edgecolor='black', facecolor='none', lw=1))

    # 添加热力图标签
    ax.text(heatmap_x, heatmap_y - heatmap_height / 2 - 0.2, "Density Map",
            ha='center', fontsize=10)

    # 连接密度估计到热力图
    ax.plot([density_x + density_width / 2, heatmap_x - heatmap_width / 2],
            [density_y, heatmap_y],
            '->', color='black', linewidth=1)

    # 特征融合模块
    fusion_x = 7
    fusion_y = 4.5
    fusion_width = 2
    fusion_height = 2

    fusion_box = patches.Rectangle((fusion_x - fusion_width / 2, fusion_y - fusion_height / 2),
                                   fusion_width, fusion_height,
                                   edgecolor='black', facecolor=colors['fusion'],
                                   alpha=0.8)
    ax.add_patch(fusion_box)

    ax.text(fusion_x, fusion_y + 0.5, "Feature Fusion",
            ha='center', va='center', fontsize=11, fontweight='bold')

    # 融合内部元素
    # 特征加权调制
    inner_y = fusion_y
    inner_width = 1.4
    inner_height = 0.5

    inner_box = patches.Rectangle((fusion_x - inner_width / 2, inner_y - inner_height / 2),
                                  inner_width, inner_height,
                                  edgecolor='black', facecolor='white',
                                  alpha=0.8)
    ax.add_patch(inner_box)

    ax.text(fusion_x, inner_y, "Density-Guided Weighting",
            ha='center', va='center', fontsize=8)

    # 连接所有特征级别到融合模块
    for y in feature_ys:
        ax.plot([feature_x + feature_width / 2, fusion_x - fusion_width / 2],
                [y, fusion_y],
                '-', color='black', linewidth=1)

    # 连接密度热力图到融合模块
    ax.plot([heatmap_x + heatmap_width / 2, fusion_x - fusion_width / 2],
            [heatmap_y, fusion_y - 0.5],
            '-->', color='black', linewidth=1.5)

    # 增强特征输出
    enhanced_x = 10
    enhanced_ys = [6, 5.5, 5, 4.5, 4]
    enhanced_width = 1.2
    enhanced_height = 0.6

    # 绘制增强特征
    for i, (level, y) in enumerate(zip(feature_levels, enhanced_ys)):
        # 不同深度的颜色
        alpha = 0.6 + 0.08 * i

        enhanced_box = patches.Rectangle((enhanced_x - enhanced_width / 2, y - enhanced_height / 2),
                                         enhanced_width, enhanced_height,
                                         edgecolor='black', facecolor=colors['output'],
                                         alpha=alpha)
        ax.add_patch(enhanced_box)

        ax.text(enhanced_x, y, f"Enhanced {level}",
                ha='center', va='center', fontsize=9)

        # 连接融合到增强特征
        ax.plot([fusion_x + fusion_width / 2, enhanced_x - enhanced_width / 2],
                [fusion_y, y],
                '->', color='black', linewidth=1)

    # 添加总输出
    output_x = 10
    output_y = 2.5
    output_width = 1.8
    output_height = 1

    output_box = patches.Rectangle((output_x - output_width / 2, output_y - output_height / 2),
                                   output_width, output_height,
                                   edgecolor='black', facecolor=colors['output'],
                                   alpha=0.9, linestyle='-')
    ax.add_patch(output_box)

    ax.text(output_x, output_y, "Density-Aware\nDetection Features",
            ha='center', va='center', fontsize=10)

    # 连接所有增强特征到总输出
    for y in enhanced_ys:
        ax.plot([enhanced_x, output_x],
                [y, output_y],
                '--', color='black', linewidth=0.8)

    # 添加说明文本 - 多尺度特征的作用
    notes_x = 1.5
    notes_y = 1.5

    scale_notes = [
        "Feature Scale Properties:",
        "P3 (Fine): Small objects, detailed textures",
        "P4-P5 (Medium): Object boundaries, structures",
        "P6-P7 (Coarse): Context, large patterns"
    ]

    for i, note in enumerate(scale_notes):
        ax.text(notes_x, notes_y - i * 0.3, note, fontsize=9)

    # 添加密度信息的作用说明
    density_notes_x = 6
    density_notes_y = 1.5

    density_notes = [
        "Density Information Benefits:",
        "• Identifies crowded regions requiring special attention",
        "• Guides feature weighting for overlapping objects",
        "• Improves small object detection in dense clusters",
        "• Enhances boundary discrimination between adjacent algae"
    ]

    for i, note in enumerate(density_notes):
        ax.text(density_notes_x, density_notes_y - i * 0.3, note, fontsize=9)

    # 添加密度区域高亮示例
    # 绘制示例区域
    highlight_x = 7
    highlight_y = 3
    highlight_radius = 0.3

    highlight = plt.Circle((highlight_x, highlight_y), highlight_radius,
                           color='red', alpha=0.3)
    ax.add_patch(highlight)

    # 添加指向标签
    ax.annotate("Dense Region\nSpecial Processing",
                xy=(highlight_x, highlight_y),
                xytext=(highlight_x + 1, highlight_y - 0.5),
                arrowprops=dict(arrowstyle="->", color='red'),
                fontsize=9, color='red')

    # 添加密度感知融合公式
    formula_x = 7
    formula_y = 6

    ax.text(formula_x, formula_y, r"$F_{enhanced} = \sum_{i} w_i(d) \cdot F_i + \alpha \cdot M_{density}$",
            fontsize=11, bbox=dict(facecolor='white', alpha=0.7, edgecolor='gray'))

    # 添加图例
    legend_elements = [
        patches.Patch(facecolor=colors['backbone'], edgecolor='black', alpha=0.8, label='Backbone Features'),
        patches.Patch(facecolor=colors['feature'], edgecolor='black', alpha=0.8, label='Multi-scale Features'),
        patches.Patch(facecolor=colors['density'], edgecolor='black', alpha=0.8, label='Density Estimation'),
        patches.Patch(facecolor=colors['fusion'], edgecolor='black', alpha=0.8, label='Feature Fusion'),
        patches.Patch(facecolor=colors['output'], edgecolor='black', alpha=0.8, label='Enhanced Output')
    ]

    ax.legend(handles=legend_elements, loc='upper right', fontsize=9)

    # 关闭坐标轴
    ax.axis('off')

    plt.tight_layout()
    plt.savefig(save_path, dpi=300, bbox_inches='tight')
    plt.show()


create_multiscale_feature_fusion()